package com.pan.crawler.impl3;

import com.pan.crawler.Page;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PageImpl3 implements Page {

    private EdgeDriver edgeDriver;

    public PageImpl3(){
        edgeDriver = new EdgeDriver();
        edgeDriver.manage().window().minimize();
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
    }

    public String clear(String content){
        String[] delRegex = new String[]{
                "最新章节 请关注达文小说网\\(\\)",
                "最新网址：www.dawensk.com"
        };
        for (int i = 0; i < delRegex.length; i++) {
            Pattern pattern = Pattern.compile(delRegex[i]);
            Matcher matcher = pattern.matcher(content);
            content = matcher.replaceAll("");
        }
        return content;
    }

    @Override
    public String get(Chapter chapter) {
        String url = chapter.getUrl();
        String content = "";
        for (int i = 0; i < 5; i++) {
            try {
                edgeDriver.navigate().to(url);
                content = edgeDriver.findElement(By.id("txt")).getText();
                break;
            }catch (Exception e){
                if (i==4) throw new RuntimeException("请求页面失败");
            }
        }
        String title ="第"+(chapter.getId()+1)+"章 "+ chapter.getTitle().replaceAll("第\\p{all}+章","");
//      不要带标题
        //        content =title+"\n\n\n\n"+ clear(content)+"\n\n\n\n\n\n";
        content = clear(content);
        return content;
    }

    @Override
    public void close() {
        edgeDriver.quit();
    }
}
